package xiao.ze.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import xiao.ze.demo.entity.User;
import xiao.ze.demo.service.impl.UserServiceImpl;
import xiao.ze.demo.utils.MyUtil;

import javax.annotation.Resource;

/**
 * @description: TODO
 * @author: Tokyo_God
 * @date: 2021/2/14 11:54
 * Role of:
 * @version: v1.0
 */
@Controller
@RequestMapping("/user")
@SessionAttributes(value = {"user"})
public class UserController {
    @Resource
    UserServiceImpl userService;

    @GetMapping("/win/main")
    public String main() {
        return "/main";
    }

    @GetMapping("/login")
    public String login() {
        System.out.println("111");
        return "/login";
    }

    @GetMapping("/register")
    public String register() {
        return "/register";
    }

    @GetMapping("/readdoc")
    public String readdoc() {
        return "/readdoc";
    }

    @PostMapping("/userLogin")
    public String userLogin(String name, String pwd, Model model) {
        User user = userService.userLogin(name, pwd);
        if (user != null) {
            model.addAttribute("user", user);
            return "redirect:/user/win/main";
        } else {
            //好像只有重定向才能到上面的login跳转方法
            return "redirect:/user/login";//重定向不会跟着原来的视图解析器来 所以地址得写绝对地址
        }
    }

    @Resource
    MyUtil util;

    @PostMapping("/userRegister")
    public String userRegister(String name, String pwd) {
        String no = util.createUserNo(6).toString();
        User user = new User(no, pwd, name);
        System.out.println(user.toString());
        int num = userService.userRegister(user);
        if (num > 0) {
            return "redirect:/user/login";
        }
        return "redirect:/user/register";
    }

}
